<!-- 签名 -->
<template>
	<view class="wrapper">
		<view class="handBtn">
			<button @click="previewCanvasImg" class="previewBtn">预览</button>
			<button @click="retDraw" class="delBtn">重写</button>
			<button @click="back" class="backBtn">返回</button>
			<button @click="subCanvas" class="subBtn">完成</button>
		</view>
		<view class="handCenter">
			<canvas class="handWriting" :disable-scroll="true" @touchstart="uploadScaleStart"
				@touchmove="uploadScaleMove" @touchend="uploadScaleEnd" canvas-id="handWriting">
				<view class="context-title" v-if="state.firstTouch">请在此处签名</view>
			</canvas>
			<canvas :disable-scroll="true" canvas-id="handWriting2" :style="handWriting2"></canvas>
		</view>
		<view class="handRight">
			<text class="handTitle">{{signatureTitle}}</text>
		</view>
	</view>
</template>

<script lang="ts" setup>
	import { uploadFile } from '@/api/request/ChooseUploadFile';
	import { ref, reactive, onMounted } from "vue"
	import { onLoad } from '@dcloudio/uni-app'
	const state = reactive({
		canvasName: 'handWriting',
		ctx: {},
		points: [], //路径点集合
		canvasWidth: 0,
		canvasHeight: 0,
		firstTouch: true, // 第一次触发
	})
	let handWriting2 = ref({
		background: '#fff',
		width: '100%',
		height: '40vh',
	})

	let signatureTitle = ref("")
	onLoad((option) => {
		signatureTitle.value = option.signatureTitle || '请签名'
	});

	onMounted(() => {
		state.ctx = uni.createCanvasContext(state.canvasName); // 创建绘图
	})
	//预览
	const previewCanvasImg = () => {
		uni.canvasToTempFilePath({ // 将画布内容保存成文件
			canvasId: 'handWriting',
			fileType: 'jpg',
			quality: 1, //图片质量
			success(res) {
				uni.previewImage({  // 预览图片
					urls: [res.tempFilePath]
				});
			}
		});
	}
	// 重写
	const retDraw = () => {
		state.ctx.clearRect(0, 0, 700, 730);
		state.ctx.draw(true);
		state.firstTouch = true
	}
	//返回
	const back = () => {
		uni.navigateBack()
	}
	//完成
	const subCanvas = () => {
		if (state.firstTouch) {
			uni.showToast({ icon: "none", title: "请先签名" })
		} else {
			state.ctx.draw(true, () => {
				uni.canvasToTempFilePath({
					canvasId: 'handWriting',
					fileType: 'png',
					quality: 1, //图片质量
					success(res) {
						rotatemg(res.tempFilePath)// 新画布 旋转
						// uploadFile({
						// 	filePath: res.tempFilePath,
						// 	success: (file) => {
						// 		uni.$emit("dzqm", file)
						// 		uni.navigateBack() //返回
						// 	},
						// 	fail: (_code, message) => {
						// 		uni.showModal({ content: "上传签名失败，" + message, showCancel: false })
						// 	},
						// })
					}
				});
			});
		}

	}

	// 笔迹开始
	const uploadScaleStart = (e) => {
		state.firstTouch = false;
		let startX = e.changedTouches[0].x;
		let startY = e.changedTouches[0].y;
		let startPoint = {
			X: startX,
			Y: startY
		};
		state.points.push(startPoint);
		//每次触摸开始，开启新的路径
		state.ctx.beginPath();
		state.ctx.setLineCap('round') // 终点样式 圆角
		state.ctx.setLineWidth(4) // 线条粗度
		state.ctx.setStrokeStyle('#1A1A1A') // 边框色
	}

	// 笔迹移动
	const uploadScaleMove = (e) => {
		state.moveX = e.changedTouches[0].x;
		state.moveX = e.changedTouches[0].y;
		let moveX = e.changedTouches[0].x;
		let moveY = e.changedTouches[0].y;
		let movePoint = {
			X: moveX,
			Y: moveY
		};
		state.points.push(movePoint); //存点
		let len = state.points.length;
		if (len >= 2) {
			draw(); //绘制路径
		}
	}
	// 笔迹结束
	const uploadScaleEnd = (e) => {
		state.points = [];
	}
	function draw() {
		let point1 = state.points[0];
		let point2 = state.points[1];
		state.points.shift();
		state.ctx.moveTo(point1.X, point1.Y);
		state.ctx.lineTo(point2.X, point2.Y);
		state.ctx.stroke();
		state.ctx.draw(true);
	}
	//旋转图片，生成新canvas实例
	function rotatemg(tempFilePaths) {
		uni.getImageInfo({
			// 获取图片的信息
			src: tempFilePaths,
			success: (res1) => {
				handWriting2.value.height  = res1.width /2 + 'px'
				handWriting2.value.width  = res1.height /2 + 'px'
				// 将canvas1的内容复制到canvas2中
				let canvasContext = uni.createCanvasContext('handWriting2')
				let rate = res1.height / res1.width
				let width = 300 / rate
				let height = 300
				canvasContext.translate(height / 2, width / 2)
				canvasContext.rotate((270 * Math.PI) / 180)
				canvasContext.drawImage(tempFilePaths, -width / 2, -height / 2, width, height)
				canvasContext.draw(true, (data) => {
					// 将之前在绘图上下文中的描述（路径、变形、样式）画到 canvas 中
					uni.canvasToTempFilePath({
						// 把当前画布指定区域的内容导出生成指定大小的图片。在 draw() 回调里调用该方法才能保证图片导出成功。
						canvasId: 'handWriting2',
						fileType: 'png',
						quality: 1, //图片质量
						success(res2) {
							uploadFile({
								filePath: res2.tempFilePath,
								mask: true,
								success: (file) => {
									uni.$emit("dzqm", file)
									uni.navigateBack() //返回
								},
								fail: (_code, message) => {
									uni.showModal({ content: "上传签名失败，" + message, showCancel: false })
								},
							})
						}
					})
				});
			}
		})
	}
</script>

<style>
	.wrapper {
		width: 100%;
		height: 80vh;
		padding: 10vh 0 0;
		overflow: hidden;
		display: flex;
		align-content: center;
		flex-direction: row;
		justify-content: center;
		font-size: 28rpx;
	}

	.handWriting {
		background: #fff;
		width: 100%;
		height: 80vh;
	}

	.handWriting2 {
		
	}

	.handRight {
		transform: rotate(90deg);
		width: 35px;
		height: 80vh;
		display: inline-flex;
		align-items: center;
		justify-content: center;
	}

	.handCenter {
		border: 4rpx dashed #e9e9e9;
		flex: 5;
		overflow: hidden;
		box-sizing: border-box;
	}

	.handTitle {
		white-space: nowrap;
		color: #666;
	}

	.handBtn button {
		font-size: 28rpx;
	}

	.handBtn {
		display: inline-flex;
		flex-direction: column;
		justify-content: space-between;
		align-content: space-between;
		flex: 1;
	}

	.previewBtn {
		position: absolute;
		top: 14vh;
		left: 0rpx;
		transform: rotate(90deg);
		color: #666;
	}

	.delBtn {
		position: absolute;
		top: 37vh;
		left: 0rpx;
		transform: rotate(90deg);
		color: #666;
	}

	.backBtn {
		position: absolute;
		bottom: 37vh;
		left: 0rpx;
		transform: rotate(90deg);
		color: #666;
	}

	.subBtn {
		position: absolute;
		bottom: 10vh;
		left: -3rpx;
		display: inline-flex;
		transform: rotate(90deg);
		background: #008ef6;
		color: #fff;
		margin-bottom: 30rpx;
		text-align: center;
		justify-content: center;
	}

	.context-title {
		line-height: 95vh;
		font-size: 60rpx;
		transform: rotate(90deg);
		overflow: hidden;
		color: #5e6267;
	}
</style>